const gulp = require('gulp');
const del = require('del');
const path = require('path');
const fs = require('fs');

const distDir = 'ChromeExtensionPublish';


// gulp.parallel gulp.series -- 全新的任务执行体系

gulp.task('clear', ()=>{
    return del([
        distDir + '/*',
    ]);
});

// 拷贝 gulp.series('clear'),
gulp.task('copy', () => {
    return gulp.src('ChromeExtension/**/*')
        .pipe(gulp.dest(distDir + '/'));
});

gulp.task('setMainfest', done => {
    let fileName = path.join(distDir, "manifest.json");
    var content = fs.readFileSync(fileName, {encoding:"utf8"});
    var config = JSON.parse(content);
    config.content_security_policy = `script-src 'self' 'unsafe-eval'; script-src-elem 'self' 'unsafe-eval' 'self'; object-src 'self'`;
    fs.writeFileSync(fileName, JSON.stringify(config, '', 2));

    done();
});

gulp.task('setOptions', done => {
    let fileName = path.join(distDir, "options.html");
    var content = fs.readFileSync(fileName, { encoding: "utf8" });

    content = content.replace("http://127.0.0.1:7000/options.js", "options.js");
    fs.writeFileSync(fileName, content);
    done();
});

gulp.task('setPopup', done => {
    let fileName = path.join(distDir, "popup.html");
    var content = fs.readFileSync(fileName, { encoding: "utf8" });

    content = content.replace("http://127.0.0.1:7000/popup.js", "popup.js");
    fs.writeFileSync(fileName, content);
    done();
});

gulp.task('publish', gulp.series('clear', 'copy', gulp.parallel('setMainfest', 'setOptions', 'setPopup')));